import com.golden.gamedev.engine.BaseAudio;
import com.golden.gamedev.object.collision.*;
import com.golden.gamedev.object.*;

public class BallBallCollision extends BasicCollisionGroup {
	public boolean collidedBall;
	public BallBallCollision() {
		super();
		pixelPerfectCollision = true;
collidedBall = false;
	
	}

	public void collided(Sprite s1, Sprite s2) {

		/**
		 * 
		 * This section of code is an adaptation concepts used in the following
		 * physics forum: www.phy.ntnu.edu.tw/ntnujava/viewtopic.php?t=19
		 * 
		 * calculates impulse of the collision along the collision' line then
		 * updates the sprites' speeds
		 * 
		 */
		collidedBall = true;
		// calculate distance of balls centers
		double dx = s2.getX() - s1.getX();
		double dy = s2.getY() - s1.getY();

		double distance = Math.sqrt(dx * dx + dy * dy);

		// generate unit vector
		double ax = dx / distance;
		double ay = dy / distance;

		// project velocities along ax and ay
		double va1 = (s1.getHorizontalSpeed() * ax + s1.getVerticalSpeed() * ay);
		double vb1 = (-1 * s1.getHorizontalSpeed() * ay + s1.getVerticalSpeed()
				* ax);
		double va2 = (s2.getHorizontalSpeed() * ax + s2.getVerticalSpeed() * ay);
		double vb2 = (-1 * s2.getHorizontalSpeed() * ay + s2.getVerticalSpeed()
				* ax);
		// find new velocities assuming perfect elasticity and equal mass
		double vaP1 = va1 + (va2 - va1);
		double vaP2 = va2 + (va1 - va2);
		// undo projection
		s1.setHorizontalSpeed(vaP1 * ax - vb1 * ay);
		s1.setVerticalSpeed(vaP1 * ay + vb1 * ax);
		s2.setHorizontalSpeed(vaP2 * ax - vb2 * ay);
		s2.setVerticalSpeed(vaP2 * ay + vb2 * ax);

		/*
		 * here is a programming fix that doesnt let the balls to get stuck
		 * together. it forces balls away from each other to avoid double
		 * collision.
		 */
		int pixels = 2;
		s1.setX(s1.getX() + (pixels * -1 * ax));
		s1.setY(s1.getY() + (pixels * -1 * ay));

		s2.setX(s2.getX() + (pixels * ax));
		s2.setY(s2.getY() + (pixels * ay));

	}
	
	public boolean collided(){
		return collidedBall;
	}
}
